<template>
  <div :class="{'resource-filter': !showMobilePage}" class="container">
    <div v-if="!showMobilePage && !filterOpen" class="is-closed filter-expend">
      <div class="filter-expend-btn" @click="switchOpen">
        <img :src="openIcon" class="img" alt=""> 搜索
      </div>
    </div>
    <transition :name="!showMobilePage?'fb-drawer-fade':''">
      <component
        v-show="filterOpen || showMobilePage"
        :is="showMobilePage?'el-drawer':'div'"
        v-bind="drawerProps"
        :class="{'filter-content': !showMobilePage, 'mobile-filter-drawer': showMobilePage}">
        <div v-if="!showMobilePage" class="is-opened filter-expend">
          <div class="filter-expend-btn" @click="switchOpen">
            <img :src="openIcon" class="img" alt="">
          </div>
        </div>
        <div :class="{'pdl-16': !showMobilePage}" class="filter-scroll">
          <!-- <div v-if="valueModelResult.length" class="filter-result">
            <div v-for="(item) in valueModelResult" :key="item.key" class="filter-tag-group">
              <span class="input-name">{{ item.name }}：</span>
              <ToolTip :content="item.value" style="max-width: 12em" />
              <div class="filter-tag-close" @click="deleteTag(item, $event)">
                <i class="el-icon-close" />
              </div>
            </div>
          </div> -->
          <el-form
            label-width="101px"
            class="filter-form"
            @submit.native.prevent>
            <FilterInfo ref="filterInfoRef" v-model="paramsObj" :dynamic-key-list="dynamicKeyList" :active-tabs="activeTabs" @queryClick="queryClick" />
          </el-form>
        </div>
        <div class="filter-btn-container">
          <template v-if="!showMobilePage">
            <el-button class="filter-search-btn" type="primary" size="small" @click="queryClick(true)">查询</el-button>
            <PresetFilter
              ref="PresetFilterRef"
              :select-value-result="valueModelResult"
              :get-preset-filter="getPresetFilter"
              :preset-type="1"
              is-resource
              use-scope-slot
              @queryClick="queryClick"/>
            <div class="filter-img" @click="queryEmpty">
              <el-tooltip :open-delay="500" content="重置筛选" placement="top">
                <img :src="resetFilterIcon" alt="">
              </el-tooltip>
            </div>
            <el-button type="primary" size="small" plain class="empty-btn-style quick-btn" @click="addFilter">添加快捷筛选</el-button>
          </template>
          <template v-else>
            <el-button class="mobile-cancel" size="small" @click="queryEmpty">重置</el-button>
            <el-button class="mobile-search-btn" type="primary" size="small" @click="queryClick(true)">查询</el-button>
          </template>
        </div>
      </component>
    </transition>
    <AddFilter ref="addRef" :select-value-result="selectValueResult" @save="setPresetFilter" />
  </div>
</template>
<script>
// api
// components
import filterInput from '@/components/Tool/input.vue';
import filterSelect from '@/components/Tool/select.vue';
import FilterInfo from './module/filterInfo';
import FilterModule from './module/filterModule';
import PresetFilter from '@/components/Tool/module/PresetFilter/index.vue';
import AddFilter from '@/components/Tool/module/PresetFilter/addDialog.vue';
// utils
import { getValueResultTag, removeEmptyFilter } from './utils';
import { mapState } from 'vuex';
// img
import presetFilterIcon from '@/assets/setting/presetFilter.png';
import presetFilterIconActive from '@/assets/setting/presetFilter_active.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import openIcon from '@/assets/medium/openIcon.png';
import filterSaveIcon from '@/assets/setting/filterSave.png';

export default {
  components: { filterInput, filterSelect, FilterInfo, FilterModule, PresetFilter, AddFilter },
  model: {
    prop: 'filterModel',
    event: 'changeVal'
  },
  provide() {
    return {
      getActiveTabs: () => this.activeTabs || 'all',
      getFilterData: () => this.paramsObj || null,
      setFilterParams: this.setFilterParams
    };
  },
  props: {
    filterModel: {
      type: Object,
      default: () => {
        return {};
      }
    },
    selectValueResult: {
      type: Array,
      default: () => []
    },
    // 平台，1:微信 2: 微博 3:小红书 4.抖音 5:更多  6:直播 7:B站
    activeTabs: {
      type: String | Number,
      default: ''
    },
    dynamicKeyList: { // 自定义字段
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      openIcon, filterSaveIcon,
      presetFilterIcon, presetFilterIconActive, resetFilterIcon,
      filterOptions: {},
      tagTreeList: [],
      queryParamsObj: {
        filterModel: {},
        filterOptions: {}
      },
      drawerVisible: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'filterOpen': state => state.medium.filterOpen,
      'showMobilePage': state => state.app.showMobilePage
    }),
    drawerProps() {
      if (!this.showMobilePage) {
        return {};
      }
      return {
        visible: this.drawerVisible,
        withHeader: false,
        appendToBody: true,
        direction: 'btt',
        size: '70%',
        beforeClose: () => { this.closeFilter(); }
      };
    },
    paramsObj: {
      get() {
        return {
          filterModel: this.filterModel,
          filterOptions: this.filterOptions
        };
      },
      set(data) {
        this.filterOptions = data.filterOptions;
        this.$emit('changeVal', data.filterModel);
      }
    },
    // 设置展示tag
    valueModelResult() {
      const paramsObj = removeEmptyFilter(JSON.parse(JSON.stringify(this.paramsObj)));
      const allFilter = this.$refs.filterInfoRef ? this.$refs.filterInfoRef.filterList : [];
      let filterList = [
        { model: 'filterModel', keyword: 'departmentNames', name: '所属经营体', type: 'input' }
      ];
      if (allFilter.length) {
        allFilter.forEach(i => {
          filterList = filterList.concat(i.children);
        });
      }
      const ans = [];
      !paramsObj.filterModel && (paramsObj.filterModel = {});
      Object.keys(paramsObj.filterModel).forEach(key => {
        const value = paramsObj.filterModel[key];
        const valueData = value.isRange ? [value.start, value.end] : paramsObj.filterModel[key];
        const data = this.getResultTag(key, valueData, filterList);
        if (data) ans.push(data);
      });
      !paramsObj.filterOptions && (paramsObj.filterOptions = {});
      Object.keys(paramsObj.filterOptions).forEach(key => {
        let data = null;
        const value = paramsObj.filterOptions[key];
        if (typeof value === 'object' && !Array.isArray(value)) {
          if (value.isCost) {
            const curFilter = filterList.find(i => i.keyword === key);
            if (curFilter) data = { name: curFilter.name, key, value: value.value };
          } else if (!value.isCost) {
            const valueData = value.isRange ? [value.start, value.end] : value.value;
            data = this.getResultTag(key, valueData, filterList);
          }
        } else {
          data = this.getResultTag(key, value, filterList);
        }
        if (data) {
          data.isOptions = true;
          ans.push(data);
        }
      });
      this.$emit('setValueModelResult', ans);
      return ans;
    }
  },
  created() {
    if (this.showMobilePage) {
      this.closeFilter();
    }
  },
  methods: {
    switchOpen() {
      // this.$store.commit('SET_FILTER_OPEN', !this.filterOpen);
      this.$store.state.medium.filterOpen = !this.filterOpen;
    },
    addFilter() {
      this.$refs.addRef && this.$refs.addRef.openDialog();
    },
    openFilter() {
      this.drawerVisible = true;
    },
    closeFilter() {
      this.drawerVisible = false;
    },
    handelParams(data) {
      const ans = {
        filterModel: data.filterModel,
        options: [],
        priceOptions: []
      };
      const allFilter = this.$refs.filterInfoRef ? this.$refs.filterInfoRef.filterList : [];
      let filterList = [];
      if (allFilter.length) {
        allFilter.forEach(i => {
          filterList = filterList.concat(i.children);
        });
      }
      if (data.filterOptions) {
        Object.keys(data.filterOptions).forEach(key => {
          const itemValue = data.filterOptions[key];
          if (Array.isArray(itemValue)) {
            const value = itemValue.join(',');
            ans.options.push({ key, value });
          } else if (typeof itemValue === 'object') {
            const temp = { key };
            if (itemValue.isRange) {
              temp.start = itemValue.start;
              temp.end = itemValue.end;
            } else {
              temp.value = itemValue.value;
            }
            if (itemValue.newOptions) temp.type = 0; // 0: 上刊价格  1:成本信息
            if (itemValue.isCost) {
              temp.costType = itemValue.costType;
              temp.type = 1;
            }
            if (itemValue.newOptions) {
              ans.priceOptions.push(temp);
            } else {
              ans.options.push(temp);
            }
          } else {
            const curFilter = filterList.find(i => i.keyword.toString() === key.toString());
            const temp = { key, value: itemValue };
            if (curFilter && curFilter.isDynamicKey) {
              temp.isDynamicKey = true;
              temp.modelKey = curFilter.modelKey;
            }
            ans.options.push(temp);
          }
        });
      }
      return ans;
    },
    // 提供父组件
    getFilterParams() {
      const paramsObj = removeEmptyFilter(this.paramsObj);
      this.queryParamsObj = paramsObj;
      const ans = this.handelParams(paramsObj);
      return ans;
    },
    getPresetFilter() {
      const paramsObj = removeEmptyFilter(this.paramsObj);
      return paramsObj;
    },
    /**
     * 事件
     */
    queryClick() {
      this.$emit('freshData');
      if (this.showMobilePage) this.closeFilter();
    },
    getResultTag(key, value, filterList) {
      const loadMoreSelectCache = this.$refs.filterInfoRef ? this.$refs.filterInfoRef.loadMoreSelectCache : {};

      return getValueResultTag(key, value, filterList, loadMoreSelectCache);
    },
    queryEmpty() {
      this.paramsObj = {
        filterModel: {},
        filterOptions: {}
      };
      this.$emit('freshData');
      if (this.showMobilePage) this.closeFilter();
    },
    deleteFilter() {
      this.paramsObj = {
        filterModel: {},
        filterOptions: {}
      };
      this.queryParamsObj = {
        filterModel: {},
        filterOptions: {}
      };
    },
    deleteTag(item) {
      const type = item.isOptions ? 'filterOptions' : 'filterModel';
      this.$set(this.paramsObj[type], item.key, null);
      delete this.paramsObj[type][item.key];
      this.queryClick();
    },
    presetFilterDefault(data) {
      if (data.params) {
        this.paramsObj = data.params;
        this.queryClick();
      } else {
        this.queryClick();
      }
    },
    getPresetInfo() {
      return {
        activeTabs: this.activeTabs || 'all',
        filterData: this.paramsObj || null
      };
    },
    setFilterParams(data) {
      // 筛选
      if (data.params) {
        this.paramsObj = _.cloneDeep(data.params);
      } else if (data) {
        this.paramsObj = _.cloneDeep(data);
      }
    },
    setPresetFilter(name) {
      if (this.$refs.PresetFilterRef) {
        this.$refs.PresetFilterRef.setData(name);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.resource-filter {
  position: fixed;
  right: 0;
  height: calc(100vh - 64px);
  top: 64px;
  z-index: 1001;
  @include flexStyle();
  &::v-deep {
    .mobile-filter-drawer {
      display: none !important;
    }
  }
}
.filter-icon-container {
  width: 24px;
  height: 24px;
  background: #f3f5fa;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  img {
    width: 14px;
  }
}
.container {
  &::v-deep {
    .mobile-filter-drawer {
      display: none !important;
    }
  }
}
.filter-expend {
  @include flexStyle($align: center);
  height: 100%;
  position: absolute;
  &.is-closed {
    right: 0;
    .filter-expend-btn {
      width: 38px;
    }
  }
  &.is-opened {
    right: 384px;
    .filter-expend-btn {
      width: 10px;
      .img {
        transform: rotate(180deg);
      }
    }
  }
  .filter-expend-btn {
    @include flexStyle($align: center, $justify:center);
    font-size: 12px;
    color: #fff;
    cursor: pointer;
    user-select: none;
    background: #406eff;
    border-radius: 4px 0px 0px 4px;
    box-shadow: 0px 2px 4px 0px #c0c9d6;
    z-index: 2;
    height: 40px;
    font-weight: 550;
    .img {
      width: 8px;
    }
  }
}
.filter-content {
  height: 100%;
  z-index: 2;
  position: relative;
  background-color: #fff;
  width: 384px;
  box-shadow: -5px 0px 6px 0px rgba(240,242,245,0.81);
}

.filter-btn-container {
  position: absolute;
  height: 56px;
  display: flex;
  align-items: center;
  bottom: 0;
  padding: 0 20px;
  border-top: 1px solid #ebeefd;
  width: 100%;
  .filter-search-btn {
    margin-right: 8px;
  }
  .filter-img {
    display: flex;
    align-items: center;
    cursor: pointer;
    img {
      width: 16px;
    }
  }
}
.filter-scroll {
  height: calc(100% - 56px);
  padding-top: 20px;
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
  &.pdl-16 {
    padding-left: 16px;
  }
}
.filter-result {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 4px;
}
.filter-tag-group {
  @include flexStyle($align: center);
  margin-bottom: 8px;
  margin-right: 8px;
  color: #406EFF;

  border-radius: 13px;
  height: 26px;
  background: #eff4ff;
  border-radius: 13px;
  padding: 0 8px;
  font-size: 12px;
  font-weight: bold;
  .filter-tag-close {
    cursor: pointer;
    margin-left: 5px;
  }
}

.mobile-filter-drawer {
  ::v-deep {
    .el-drawer {
      border-radius: 20px 20px 0px 0px;
    }
  }
  .filter-scroll {
    padding-left: 10px;
    height: calc(100% - 49px);
  }
  .filter-btn-container {
    @include flexStyle($align: center, $justify: center);
    width: 100%;
    height: 49px;
  }
  .mobile-cancel {
    width: 120px;
    height: 36px;
    font-size: 16px;
    color: #406EFF;
    border-color: #406EFF !important;
    border-radius: 4px;
  }
  .mobile-search-btn {
    flex: 1;
    height: 36px;
    font-size: 16px;
    border-radius: 4px;
  }
}
@keyframes drawer-fade-in {
	0% {
    // opacity:0;
    transform:translate(100%,0)
  }
  100% {
    // opacity:1;
    transform:translate(0,0)
  }
}
.fb-drawer-fade-enter-active {
  animation: drawer-fade-in .3s;
}

.fb-drawer-fade-leave-active  {
 animation: drawer-fade-in .3s reverse;
}

@keyframes expend-fade-in {
	0% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}

.operate-btn {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-right: 8px;
  @include flexStyle(center, center);
  &.active {
    background-color: #EDEEF2;
    border-radius: 4px;
  }
  .operate-icon {
    width: 16px;
    height: 16px;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  padding: 7px 12px;
  text-align: center;
}
.quick-btn {
  position: absolute;
  right: 20px;
}
</style>
